const app = getApp(); // 获取全局应用实例

Page({
  data: {
    photoList: [], // 图片路径列表
    currentIndex: 0, // 当前显示的图片索引
    imageStyles: [], // 存储每张图片的旋转角度
    userId:null,
    show:false,
    description:"",//描述
    address:"",//地址
    identity:"",//身份证号
    birth:"",// 出生日期
    name:"",//姓名
    sex:"",//性别
    period:"",//有效期限
    nation:"",//民族
    jiguan:"",//机关
    cutEdgeImagePath:"",//切边图像
    avatarImagePath:""//头像
  },

  onLoad: function(options) {
    const userInfo = wx.getStorageSync('userInfo');
    console.log('userid传到怕照页面：', userInfo);
    this.setData({
      userId: userInfo.userId, // 设置用户ID
    });

    // 将上一个页面的路径保存在全局变量中
    const pages = getCurrentPages();
    const prevPage = pages[pages.length - 2];
    app.globalData.prevPage = prevPage.route;
    // 从全局变量中读取图片路径列表
    const photoList = app.globalData.photoList || [];
    // 初始化旋转角度数组，默认为0
    const imageStyles = new Array(photoList.length).fill("transform: rotate(0deg);");
    this.setData({
      photoList: photoList,
      imageStyles: imageStyles,
      currentIndex: 0 // 默认显示第一张图片
    });
  },
  prevPhoto: function() {
    // 显示上一张图片
    let index = this.data.currentIndex;
    index = index - 1 < 0 ? this.data.photoList.length - 1 : index - 1;
    this.setData({
      currentIndex: index
    });
  },
  nextPhoto: function() {
    // 显示下一张图片
    let index = this.data.currentIndex;
    index = index + 1 >= this.data.photoList.length ? 0 : index + 1;
    this.setData({
      currentIndex: index
    });
  },
  // 继续添加功能
  continueAdd:function() {
    console.log("继续添加")
    wx.navigateBack();
  },

  // 删除本页功能
  deletePage() {
    let { photoList, currentIndex } = this.data;
    if (photoList.length === 1) {
      wx.showToast({
        title: '亲，至少需要一张图片',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    photoList.splice(currentIndex, 1); // 删除当前页图片
    if (currentIndex >= photoList.length && currentIndex > 0) {
      currentIndex--; // 如果删除了最后一页，将索引前移
    }
    this.setData({
      photoList: photoList,
      currentIndex: currentIndex
    });
  },

  // 信息提取功能
  infoGet: function() {

    const userId = this.data.userId; // 获取用户ID
    const currentPhoto = this.data.photoList[this.data.currentIndex]; // 获取当前显示图片的路径
    const that = this;
    // 将图片转换为 base64 格式
    wx.getFileSystemManager().readFile({
      filePath: currentPhoto,
      encoding: 'base64',
      success: function(res) {
        const base64ImageData = res.data; // 获取图片的 base64 数据
        // console.log(base64ImageData)
        // 发送请求给后端
        wx.request({
          url: 'http://localhost:8080/ft/textin/cert_classify',
          method: 'POST',
          data: {
            base64ImageData: base64ImageData,
            userId: userId
          },
          success: function(res) {
            // console.log('信息提取请求成功', res.data.data);
            // const responseDataString = res.data.data; // 从后端返回的数据
            // const responseData = JSON.parse(responseDataString);
            const responseData = res.data.data ? JSON.parse(res.data.data) : null;
            if (!responseData || Object.keys(responseData).length === 0) {
              wx.showToast({
                title: '亲，只有身份证才有信息提取哟！',
                icon: 'error',
                duration: 2000
              });
              that.setData({ show: false });
              return;
            }
            console.log(responseData)
          // 将responseData存储到infoData中
          that.setData({
            show: true,
             description:responseData['type_description'],
             address:responseData['住址'],
             name:responseData['姓名'],
             identity:responseData['公民身份证号'],
             birth:responseData['出生'],
             sex:responseData['性别'],
             period:responseData['有效期限'],
             nation:responseData['民族'],
             jiguan:responseData['签发机关']

          });
          const avatarImageData = responseData['头像'] || '';
          if (avatarImageData) {
            that.showImage(avatarImageData, 'avatar');
          }
          // 处理切边图像
          const cutEdgeImageData = responseData['切边图像'] || '';
          if (cutEdgeImageData) {
            that.showImage(cutEdgeImageData, 'cutEdge');
          }
          },
          fail: function(err) {
           console.log("错误信息",err)
          }
        });
      },
      fail: function(err) {
        console.error('读取图片文件失败', err);
      }
    });
  },
// 显示并保存图像（头像或切边图像）
showImage: function(base64ImageData, type) {
  const that = this;
  const fsm = wx.getFileSystemManager();
  // 根据类型设置文件名后缀
  const suffix = type === 'avatar' ? '_avatar.jpg' : '_cutEdge.jpg';
  const fileName = `${Date.now()}${suffix}`; // 生成随机文件名
  const filePath = `${wx.env.USER_DATA_PATH}/${fileName}`; // 构建文件路径

  fsm.writeFile({
    filePath: filePath,
    data: base64ImageData,
    encoding: 'base64',
    success: function(res) {
      console.log('保存临时文件成功', res);
      // 根据类型更新对应的数据路径
      if (type === 'avatar') {
        that.setData({
          avatarImagePath: filePath // 保存临时文件路径
        });
      } else if (type === 'cutEdge') {
        that.setData({
          cutEdgeImagePath: filePath // 保存临时文件路径
        });
      }
    },
    fail: function(err) {
      console.error('保存临时文件失败', err);
    }
  });
},

  
 // 旋转功能
rotate() {
  const { currentIndex, imageStyles } = this.data;
  const currentRotation = parseInt(imageStyles[currentIndex].split('(')[1].split('deg')[0]);
  const newRotation = currentRotation + 90;
  imageStyles[currentIndex] = "transform: rotate(" + newRotation + "deg);";
  this.setData({
    imageStyles: imageStyles
  });
},
confirm: function() {
  const { photoList, imageStyles } = this.data;
  const processedPhotos = photoList.map((photo, index) => ({
    path: photo,
    rotation: parseInt(imageStyles[index].split('(')[1].split('deg')[0])
  }));
  // 将图片数据传递到下一个页面
  wx.navigateTo({
    url: '/pages/scan/output/output?photos=' + JSON.stringify(processedPhotos),
  });
},
onClose() {
  this.setData({ show: false });
},
});
